#!/usr/bin/env python
#
# Copyright (C) 2005-2020 ABINIT Group (Yann Pouillon)
#
# This file is part of the ABINIT software package. For license information,
# please see the COPYING file in the top-level directory of the ABINIT source
# distribution.
#
from __future__ import print_function, division, absolute_import #, unicode_literals

try:
    from ConfigParser import ConfigParser,NoOptionError
except ImportError:
    from configparser import ConfigParser,NoOptionError
from time import gmtime,strftime

import os
import re
import sys

class MyConfigParser(ConfigParser):

  def optionxform(self,option):
    return str(option)

# ---------------------------------------------------------------------------- #

#
# Subroutines
#

# Makefile header
def makefile_template(name,stamp,b_name):

  return """#
# Makefile for ABINIT                                      -*- Automake -*-
# Generated by %s on %s

#
# IMPORTANT NOTE
#
# Any manual change to this file will systematically be overwritten.
# Please modify the %s script or its config file instead.
#

# Delegate build to bindings' own Makefile
# See config/makefiles/%s.am for details
all-local: bindings-ready

EXTRA_DIST = @SOURCES@

CLEANFILES = bindings-ready @PACKAGE@-*.tar.gz

-include ../config.mk
""" % (name,stamp,name,b_name)



def top_template(name,stamp,b_list):

  targets = ""
  for bnd in b_list:
    targets += "\n# Individual target for %s\n" % bnd
    targets += "%s-bindings:\n\tcd %s && $(MAKE) all @SET_MAKE@\n" % \
      (bnd,bnd)

  return """#
# Makefile for ABINIT                                      -*- Automake -*-
# Generated by %s on %s

#
# IMPORTANT NOTE
#
# Any manual change to this file will systematically be overwritten.
# Please modify the %s script or its config file instead.
#

AM_DISTCHECK_CONFIGURE_FLAGS = \\
  @bnd_ac_distcheck@

SUBDIRS =%s
%s
""" % (name,stamp,name," \\\n  " + " \\\n  ".join(b_list),targets)



# ---------------------------------------------------------------------------- #

#
# Main program
#

# Initial setup
my_name    = "make-makefiles-bindings"
my_configs = ["config/specs/bindings.conf"]

# Check if we are in the top of the ABINIT source tree
if ( not os.path.exists("configure.ac") or
     not os.path.exists("config/specs/bindings.conf") ):
  print("%s: You must be in the top of an ABINIT Bindings source tree." % \
    my_name)
  print("%s: Aborting now." % my_name)
  sys.exit(1)

# Read config file(s)
for cnf_file in my_configs:
  if ( os.path.exists(cnf_file) ):
    if ( re.search("\.cf$",cnf_file) ):
      exec(compile(open(cnf_file).read(), cnf_file, 'exec'))
  else:
    print("%s: Could not find config file (%s)." % (my_name,cnf_file))
    print("%s: Aborting now." % my_name)
    sys.exit(2)

# What time is it?
now = strftime("%Y/%m/%d %H:%M:%S +0000",gmtime())

# Init
cnf = MyConfigParser()
cnf.read(my_configs[0])
abinit_bindings = cnf.sections()
abinit_bindings.sort()

# Process each bindings blob
for bnd in abinit_bindings:

  # Init
  bnd_dir = "%s" % (bnd)
  sources = ""
  targets = ""
  cleans = ""
  sep = " \\\n  "

  # Extract bindings information
  try:
    bnd_bins = cnf.get(bnd,"binaries").split()
  except NoOptionError:
    bnd_bins = None
  try:
    bnd_hdrs = cnf.get(bnd,"headers").split()
  except NoOptionError:
    bnd_hdrs = None
  try:
    bnd_libs = cnf.get(bnd,"libraries").split()
  except NoOptionError:
    bnd_libs = None
  try:
    bnd_mods = cnf.get(bnd,"modules").split()
  except NoOptionError:
    bnd_mods = None
  try:
    bnd_srcs = cnf.get(bnd,"sources").split()
  except NoOptionError:
    bnd_srcs = None

  # Update list of files to clean
  if ( bnd_bins != None ):
    cleans += sep+sep.join(bnd_bins)
  if ( bnd_hdrs != None ):
    cleans += sep+sep.join(bnd_hdrs)
  if ( bnd_libs != None ):
    cleans += sep+sep.join(bnd_libs)
  if ( bnd_mods != None ):
    cleans += sep+sep.join(bnd_mods)
  if ( bnd_srcs != None ):
    sources += sep+sep.join(bnd_srcs)

  # Import and update template 
  makefile = makefile_template(my_name,now,bnd)
  makefile = re.sub("@SOURCES@",sources,makefile)
  makefile = re.sub("@CLEANS@",cleans,makefile)
  makefile = re.sub("@PACKAGE@",bnd,makefile)

  # Add hand-written makefile providing the bindings-ready target
  add = "config/makefiles/%s.am" % bnd
  if ( os.path.exists(add) ):
    makefile += "\n" + open(add, "rt").read()
  else:
    sys.stderr.write("%s: Error: file not found\n    %s\n" % \
      (my_name,add))
    sys.exit(1)

  # Add RoboDOC header
  hdr = "%s/_%s_" % (bnd_dir,bnd)
  if ( os.path.exists(hdr) ):
    makefile += "\nEXTRA_DIST += _%s_\n" % (bnd)

  mf = open(bnd_dir+"/Makefile.am", "wt")
  mf.write(makefile)
  mf.close()

# Generate top makefile
maketop = top_template(my_name,now,abinit_bindings)
mf = open("Makefile.am", "wt")
mf.write(maketop)
mf.close()
